package com.suse.warmstill.service.mq;

import com.alibaba.fastjson.JSON;
import com.suse.warmstill.common.enums.MqQueueConstants;
import com.suse.warmstill.common.enums.RedisEnum;
import com.suse.warmstill.entity.ChatMsg;
import com.suse.warmstill.vo.MessageInfo;
import com.suse.warmstill.vo.MqMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 黄靖
 * @author 2023-02-13 07:41
 * description:
 **/
@Component
@Slf4j
public class mqConsumer {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @RabbitListener(queuesToDeclare = @Queue(MqQueueConstants.CHATSTORE))
    public void chatSave(MqMessage mqMessage) {
        ChatMsg chatMsg = JSON.parseObject(mqMessage.getBody(), ChatMsg.class);


        String chatList = redisTemplate.opsForValue().get(RedisEnum.CHAT_ROOM + mqMessage.getUuid());
        List<ChatMsg> list = null;
        if (ObjectUtils.isEmpty(chatList)) {

            list = new ArrayList<>();
            list.add(chatMsg);
            String newlist = JSON.toJSONString(list);
            redisTemplate.opsForValue().set(RedisEnum.CHAT_ROOM + mqMessage.getUuid(), newlist);
        }
        list = JSON.parseArray(chatList, ChatMsg.class);
        list.add(chatMsg);
        redisTemplate.opsForValue().set(RedisEnum.CHAT_ROOM + mqMessage.getUuid(), JSON.toJSONString(list), 30, TimeUnit.DAYS);
    }


}
